// Created by Xslt generator for Eclipse.
// XSL :  not found (java.io.FileNotFoundException:  (The system cannot find the path specified))
// Default XSL used : easystruts.jar$org.easystruts.xslgen.JavaClass.xsl

package com.ba360.struts.action;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.TimeZone;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import javax.media.jai.operator.FileLoadDescriptor;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.transaction.util.FileHelper;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.ba360.portal.common.PortalConstants;
import com.ba360.portal.database.DBConnectionImpl;
import com.ba360.portal.database.dbo.Classifieds;
import com.ba360.portal.database.dbo.User;
import com.ba360.portal.util.Formatter;
import com.ba360.portal.util.Log;
import com.ba360.struts.form.NewAdRecord;
import com.sun.media.jai.codec.SeekableStream;

/**
 * NewAdRecordAction.java created by EasyStruts - XsltGen.
 * http://easystruts.sf.net created on 05-02-2004
 *
 * XDoclet definition:
 *
 * @struts:action path="/" name="Form" input="/jsp/PostClassifieds.jsp"
 *                validate="true"
 * @struts:action-forward name="/portal/publishadv.do"
 *                        path="/portal/publishadv.do"
 * @struts:action-forward name="/portal/NewAdv.do" path="/portal/NewAdv.do"
 */
public class NewAdRecordAction extends Action {

	// --------------------------------------------------------- Instance
	// Variables

	// --------------------------------------------------------- Methods
	private HttpServletRequest request;
	private HttpSession session;

	/**
	 * Method execute
	 *
	 * @param ActionMapping
	 *            mapping
	 * @param ActionForm
	 *            form
	 * @param HttpServletRequest
	 *            request
	 * @param HttpServletResponse
	 *            response
	 * @return ActionForward
	 * @throws Exception
	 */

	public static String PUBLISH_AD = "PublishAd";

	public int postID = 0;

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		this.request = request;
		this.session = request.getSession();
		
		String forward = "success";
		try {
		String cancel = request.getParameter("org.apache.struts.taglib.html.CANCEL");
		if (cancel!=null && cancel.equals("Cancel"))
		{
			ActionForward af = new ActionForward();
			af.setContextRelative(true);
			af.setRedirect(true);
			af.setName("Cancel");
			af.setPath("/portal/index.do");
			return af;
		}
		NewAdRecord newAdRecord = (NewAdRecord) form;
		//throw new UnsupportedOperationException("Generated method
		// 'execute(...)' not implemented.");
		String category_id = request.getParameter("PostingType");
		Log.init(this.getClass());

		if (category_id != null) {

			if (category_id.equals("1")) {
				forward = "housing";
				Log.info("Setting CatType in new Ad record");
				request.setAttribute("catType", "housing");
			} else if (category_id.equals("2")) {
				forward = "forsale";
				request.setAttribute("catType", "forsale");
			}/* else if (category_id.equals("3")) {
				forward = "personals";
			} else if (category_id.equals("4")) {
				forward = "jobs";
			} else if (category_id.equals("5")) {
				forward = "education";
			} else if (category_id.equals("6")) {
				forward = "services";
			} else if (category_id.equals("7")) {
				forward = "community";
			}*/
			else
			{
				forward = "services";
			}
		}
		Connection conn = null;
		Statement stmt = null;
		DBConnectionImpl dbConn = new DBConnectionImpl();
		conn = dbConn.getConnection();
		stmt = conn.createStatement();
		String action = request.getParameter(PortalConstants.ACTION);		
		// Get the path to the /Users/images from the servlet context.
        ServletContext theApplicationsServletContext =
                (ServletContext) this.getServlet().getServletContext();
        int userId;
        if (session.getAttribute(PortalConstants.USER) != null) {
        	userId = (int) ((User) session.getAttribute(PortalConstants.USER)).getUserId();
        } else {
            userId = getUserId((String) session.getAttribute("AdvId"), stmt);
		}
        String realPath = theApplicationsServletContext
				.getRealPath("\\droik\\Users\\images\\" + userId);
        String tmpPath = realPath;
        File dir = new File(realPath);

		if (action == null) {

			String subCatId = request.getParameter("CatType");
			String city_id = request.getParameter("city_id");

			newAdRecord.setCategory_id(category_id);
			newAdRecord.setSubCat_id(subCatId);
			newAdRecord.setCity_id(city_id);
			//}

			String catName = dLookUp(stmt, "categories", "name", "category_id="
					+ Integer.parseInt(category_id));
			String subCatName = dLookUp(stmt, "categories", "name",
					"category_id=" + Integer.parseInt(subCatId));
			String city = dLookUp(stmt, "lookup_city", "cityname", "city_id="
					+ Integer.parseInt(city_id));

			newAdRecord.setCatName(catName);
			newAdRecord.setSubCatName(subCatName);
			newAdRecord.setCity(city);
			//newAdRecord.reset(mapping,request);
			tmpPath = realPath + "/" + userId;
			dir = new File(tmpPath);;
			if (dir.isDirectory()) {
				File[] dirs = dir.listFiles();
				for (int i = 0; i < dirs.length; i++) {
					if (dirs[i].isDirectory()) {
						File[] files = dirs[i].listFiles();
						for (int j = 0; j < files.length; j++) {
							files[j].delete();
						}
					}

					dirs[i].delete();
				}
				dir.delete();
			}
			postID = 0;
			session.removeAttribute("AdvId");

		}
		if (action != null) {

			if (action.equals(PUBLISH_AD)) {
				forward = "ViewAd";
				String advId = (String) session.getAttribute("AdvId");
				if (advId != null) {
					stmt.execute("delete from ads where ad_id="
							+ Integer.parseInt(advId));
				}

				String insIntoAd = "insert into ads(house_type,contact_number,contact_name,Contact_email,city_id,member_id,"
						+ "category_id,name,sqft,ad_description,date_posted,price,active_until,isanonymize) values(";
				Log.info(insIntoAd);
				String houseType = "'" + newAdRecord.getHouseType() + "',";
				String conNumber = "'" + Formatter.formatString(newAdRecord.getContactNumber()) + "',";
				String conName = "'" + Formatter.formatString(newAdRecord.getContactName()) + "',";
				String conEmail = "'" + Formatter.formatString(newAdRecord.getContactEmail()) + "',";
				int city_id = Integer.parseInt(newAdRecord.getCity_id());
				User user = (User) session.getAttribute(PortalConstants.USER);
				double memId = user.getUserId();
				int catId = Integer.parseInt(newAdRecord.getSubCat_id());
				String name = "'" + Formatter.formatString(newAdRecord.getTitle()) + "',";
				String sqft = "'" + newAdRecord.getSquareFeet() + "',";
				String adDesc = "'" + Formatter.formatString(newAdRecord.getPostDesc()) + "',";
				//java.sql.Date dt = new java.sql.Date()
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");

				String price = "'" + newAdRecord.getPrice().substring(2) + "',";

				/*
				 * String datePosted1 = newAdRecord.getDatePosted(); String year =
				 * datePosted1.substring(6); String month =
				 * datePosted1.substring(0,2); String day =
				 * datePosted1.substring(3,5);
				 *
				 *
				 *
				 * String dateP = year+"-"+month+"-"+day;
				 */

				String datePosted = "'" + sdf.format(new Date()) + "',";

				String activeUntil1 = newAdRecord.getActiveUntil();
				String year = activeUntil1.substring(6);
				String day = activeUntil1.substring(0, 2);
				String month = activeUntil1.substring(3, 5);
				String dateA = year + "-" + month + "-" + day;
				String activeUntil = "'" + dateA + "',";
				String isanonymize = "'" + newAdRecord.getIsAnonymize() + "')";
				Log.info(insIntoAd + houseType + conNumber + conName + conEmail
						+ city_id + "," + memId + "," + catId + "," + name
						+ sqft + adDesc + datePosted + price + activeUntil
						+ isanonymize);
				try {

					stmt.execute(insIntoAd + houseType + conNumber + conName
							+ conEmail + city_id + "," + memId + "," + catId
							+ "," + name + sqft + adDesc + datePosted + price
							+ activeUntil + isanonymize);

				} catch (Exception e) {
					Log.error(insIntoAd + houseType + conNumber + conName
							+ conEmail + city_id + "," + memId + "," + catId
							+ "," + name + sqft + adDesc + datePosted + price
							+ activeUntil + isanonymize);
				}
			} else if (action.equals("EditAd")) {
				//forward=
				String adId = request.getParameter("advId");
				int advId = Integer.parseInt(adId);
				postID = advId;
				session.setAttribute("AdvId", advId + "");
				String action1 = request.getParameter("action1");
				if("RePublishAdv".equals(action1)) {
					forward = rePublishAdInfo(conn, stmt, advId, newAdRecord);
				} else {
					forward = "housing";
					adInfo(conn, stmt, advId, newAdRecord);
				}
			} else if (action.equals("DisplayAd")) {
				//forward=
				forward = "DisplayAd";
				int advId = Integer.parseInt(request.getParameter("advId"));
				//session.setAttribute("AdvId", advId + "");
				adInfo(conn, stmt, advId, newAdRecord);
			} else if (action.equals("DeleteAd")) {
				//forward=
				String submit = request.getParameter("Submit");
				if (submit!=null && submit.equals("Delete"))
				{

					forward = "MyAds";
					int advId = Integer.parseInt(request.getParameter("advId"));
					//session.setAttribute("AdvId", advId + "");
					int memId = newAdRecord.getMemberId();
					Log.info("Logged in userid: "+userId+"  admemberid: "+memId);
					//newAdRecord.get
					stmt.execute("delete from ads where ad_id=" + advId);
					// Deleting image directory for this adv post.
					File dstDir = new File(realPath + "/" + advId + "/");
					if (dstDir.isDirectory()) {
						File[] dirs = dstDir.listFiles();
						for (int i = 0; i < dirs.length; i++) {
							if (dirs[i].isDirectory()) {
								File[] files = dirs[i].listFiles();
								for (int j = 0; j < files.length; j++) {
									files[j].delete();
								}
							}

							dirs[i].delete();
						}
						dstDir.delete();
					}
				}
				else if (submit!=null && submit.equals("Cancel"))
				{
					forward="MyAds";
				}
			}
			if (action.equals("PostAd") || action.equals(PUBLISH_AD)) {

				double memId = userId;

				dir.mkdir();

				if(postID==0) {

					String adId = request.getParameter("advId");
					if (adId != null && adId.length() > 0) {
						postID = Integer.parseInt(adId);
					} else {
						postID = (int) memId;
					}
				}

				tmpPath = realPath + "/" + postID;
				dir = new File(tmpPath);
				dir.mkdir();

				// Process the Form Files
				FormFile myFile = newAdRecord.getTheFile1();
				String contentType;
				String fileName;
				int fileSize;
				InputStream in;
				File out;
				if(myFile != null) {
					contentType = myFile.getContentType();
					fileName    = myFile.getFileName();
					fileSize    = myFile.getFileSize();

					System.out.println("contentType: " + contentType);
					System.out.println("File Name: " + fileName);
					System.out.println("File Size: " + fileSize);

					in = myFile.getInputStream();
					if(fileSize > 0) {
						dir = new File(tmpPath + "/" + 1);
						if (dir.isDirectory()) {
							File[] files = dir.listFiles();
							for (int j = 0; j < files.length; j++) {
								files[j].delete();
							}
						}
						dir.mkdir();
						out = new File(tmpPath + "/" + 1 + "/" + fileName);
						FileHelper.copy(in, out);
						in.close();

						compressFile(tmpPath + "/" + 1, out, fileName);

						out.delete();
						in = null;
					}
				}

				newAdRecord.setTheFile1(null);
				myFile = newAdRecord.getTheFile2();

				if(myFile != null) {
					contentType = myFile.getContentType();
					fileName    = myFile.getFileName();
					fileSize    = myFile.getFileSize();

					System.out.println("contentType: " + contentType);
					System.out.println("File Name: " + fileName);
					System.out.println("File Size: " + fileSize);

					in = myFile.getInputStream();
					if(fileSize > 0) {
						dir = new File(tmpPath + "/" + 2);
						if (dir.isDirectory()) {
							File[] files = dir.listFiles();
							for (int j = 0; j < files.length; j++) {
								files[j].delete();
							}
						}
						dir.mkdir();
						out = new File(tmpPath + "/" + 2 + "/" + fileName);
						FileHelper.copy(in, out);
						in.close();

						compressFile(tmpPath + "/" + 2, out, fileName);

						out.delete();
						out = null;
						in = null;
					}
				}

				newAdRecord.setTheFile2(null);
				myFile = newAdRecord.getTheFile3();

				if(myFile != null) {
					contentType = myFile.getContentType();
					fileName    = myFile.getFileName();
					fileSize    = myFile.getFileSize();

					System.out.println("contentType: " + contentType);
					System.out.println("File Name: " + fileName);
					System.out.println("File Size: " + fileSize);

					in = myFile.getInputStream();
					if(fileSize > 0) {
						dir = new File(tmpPath + "/" + 3);
						if (dir.isDirectory()) {
							File[] files = dir.listFiles();
							for (int j = 0; j < files.length; j++) {
								files[j].delete();
							}
						}
						dir.mkdir();
						out = new File(tmpPath + "/" + 3 + "/" + fileName);
						FileHelper.copy(in, out);
						in.close();

						compressFile(tmpPath + "/" + 3, out, fileName);

						out.delete();
						out = null;
						in = null;
					}
				}

				newAdRecord.setTheFile3(null);
				myFile = newAdRecord.getTheFile4();

				if(myFile != null) {
					contentType = myFile.getContentType();
					fileName    = myFile.getFileName();
					fileSize    = myFile.getFileSize();

					System.out.println("contentType: " + contentType);
					System.out.println("File Name: " + fileName);
					System.out.println("File Size: " + fileSize);

					in = myFile.getInputStream();
					if(fileSize > 0) {
						dir = new File(tmpPath + "/" + 4);
						if (dir.isDirectory()) {
							File[] files = dir.listFiles();
							for (int j = 0; j < files.length; j++) {
								files[j].delete();
							}
						}
						dir.mkdir();
						out = new File(tmpPath + "/" + 4 + "/" + fileName);
						FileHelper.copy(in, out);
						in.close();

						compressFile(tmpPath + "/" + 4, out, fileName);

						out.delete();
						out = null;
						in = null;
					}
				}

				newAdRecord.setTheFile4(null);
				myFile = newAdRecord.getTheFile5();

				if(myFile != null) {
					contentType = myFile.getContentType();
					fileName    = myFile.getFileName();
					fileSize    = myFile.getFileSize();

					System.out.println("contentType: " + contentType);
					System.out.println("File Name: " + fileName);
					System.out.println("File Size: " + fileSize);

					in = myFile.getInputStream();
					if(fileSize > 0) {
						dir = new File(tmpPath + "/" + 5);
						if (dir.isDirectory()) {
							File[] files = dir.listFiles();
							for (int j = 0; j < files.length; j++) {
								files[j].delete();
							}
						}
						dir.mkdir();
						out = new File(tmpPath + "/" + 5 + "/" + fileName);
						FileHelper.copy(in, out);
						in.close();

						compressFile(tmpPath + "/" + 5, out, fileName);

						out.delete();
						out = null;
						in = null;
					}
				}

				newAdRecord.setTheFile5(null);
				myFile = newAdRecord.getTheFile6();

				if(myFile != null) {
					contentType = myFile.getContentType();
					fileName    = myFile.getFileName();
					fileSize    = myFile.getFileSize();

					System.out.println("contentType: " + contentType);
					System.out.println("File Name: " + fileName);
					System.out.println("File Size: " + fileSize);

					in = myFile.getInputStream();
					if(fileSize > 0) {
						dir = new File(tmpPath + "/" + 6);
						if (dir.isDirectory()) {
							File[] files = dir.listFiles();
							for (int j = 0; j < files.length; j++) {
								files[j].delete();
							}
						}
						dir.mkdir();
						out = new File(tmpPath + "/" + 6 + "/" + fileName);
						FileHelper.copy(in, out);
						in.close();

						compressFile(tmpPath + "/" + 6, out, fileName);

						out.delete();
						out = null;
						in = null;
					}
				}

				newAdRecord.setTheFile6(null);
				System.out.println("Finished uploading and compressing files");

				//	moving the file from tmp folder to posting_id folder
				if (PUBLISH_AD.equals(action)) {
					String statement = "SELECT max(ad_id) maxad_id FROM ads";
					ResultSet rs = stmt.executeQuery(statement);
					if (rs.next()) {
						File srcDir = new File(realPath + "/" + postID + "/");
						postID = 0;
						String ad_id = rs.getString("maxad_id");
						File dstDir = new File(realPath + "/" + ad_id);
						if (dstDir.isDirectory()) {
							dstDir.delete();
						}
						// Move file to new directory
						boolean success = srcDir.renameTo(dstDir);
						if (!success) {
							// File was not successfully moved
							Log.info("File was not successfully moved");
							System.out.println("File was not successfully moved");
						}
						//storing the comments into the database
						stmt.execute("update ads set comment1 = '"
									+ request.getParameter("comment1")
									+ "', comment2 = '"
									+ request.getParameter("comment2")
									+ "', comment3 = '"
									+ request.getParameter("comment3")
									+ "', comment4 = '"
									+ request.getParameter("comment4")
									+ "', comment5 = '"
									+ request.getParameter("comment5")
									+ "', comment6 = '"
									+ request.getParameter("comment6")
									+ "' where ad_id= " + ad_id);
						stmt.close();
						rs.close();
					}
				}
			}
		}
		conn.close();
		} catch (Exception e) {
			System.out.println(e);
		}

		return mapping.findForward(forward);

	}

	private void adInfo(Connection conn, Statement stmt, int advId,
			NewAdRecord newAdRecord)
			throws Exception {

		User user = (User)session.getAttribute(PortalConstants.USER);
		String action = request.getParameter(PortalConstants.ACTION);
		String statement = "select * from ads where ad_id=" + advId+" order by date_posted desc";
		if (action.equals("EditAd"))
		{
			statement = "select * from ads where ad_id=" + advId+" and member_id="+user.getUserId()+" order by date_posted desc";
		}
		ResultSet rs = stmt
				.executeQuery(statement);
		while (rs.next()) {

			Classifieds thisAd = new Classifieds();
			Statement stmt1 = conn.createStatement();
			//String action = request.getParameter(PortalConstants.ACTION);
			if (action != null && action.equals("EditAd")) {
				newAdRecord.setActiveUntil(new SimpleDateFormat("dd-MM-yyyy")
						.format(rs.getDate(thisAd.ADV_ACTIVEUNTIL)));
			} else {
				newAdRecord
						.setActiveUntil(new SimpleDateFormat("yyyy.MMMMM.dd")
								.format(rs.getDate(thisAd.ADV_ACTIVEUNTIL)));
			}
			newAdRecord.setAdId(rs.getString("ad_id"));
			newAdRecord.setMemberId(rs.getInt("member_id"));
			SimpleDateFormat sdf = new SimpleDateFormat("MMM,dd hh:mm aaa");
			TimeZone tz = TimeZone.getTimeZone("GMT+05:30");
			tz.useDaylightTime();
			sdf.setTimeZone(tz);
			newAdRecord.setDatePosted(sdf.format(rs
					.getTimestamp(thisAd.ADV_DATE)));
			newAdRecord.setSubCat_id(rs.getString(thisAd.ADV_CATID));
			newAdRecord.setContactEmail(rs.getString(thisAd.ADV_CONTACTEMAIL));
			newAdRecord.setContactName(rs.getString(thisAd.ADV_CONTACTNAME));
			newAdRecord.setContactNumber(rs.getString(thisAd.ADV_CONTACTNUM));
			newAdRecord.setPostDesc(rs.getString(thisAd.ADV_TRADEDESC));
			newAdRecord.setPrice(rs.getString(thisAd.ADV_PRICE));
			newAdRecord.setTitle(rs.getString(thisAd.ADV_TITLE));
			newAdRecord.setSquareFeet(rs.getString(thisAd.ADV_SQFT));
			newAdRecord.setHouseType(rs.getString(thisAd.ADV_HOUSETYPE));
			String isanonymize = rs.getString("isanonymize");
			if (isanonymize.equals("on")) {
				newAdRecord.setIsAnonymize("on");
			} else {
				newAdRecord.setIsAnonymize(null);
			}

			String parent_cat_id = dLookUp(stmt1, "categories",
					"par_category_id", "category_id="
							+ newAdRecord.getSubCat_id());
			int parCatId = Integer.parseInt(parent_cat_id);
			if (parCatId == 1) {
				Log.info("Setting CatType");

				request.setAttribute("catType", "housing");

			}
			newAdRecord.setCategory_id(parent_cat_id);

			String catName = dLookUp(stmt1, "categories", "name",
					"category_id=" + newAdRecord.getCategoryId());
			String subCatName = dLookUp(stmt1, "categories", "name",
					"category_id=" + newAdRecord.getSubCat_id());
			String city = dLookUp(stmt1, "lookup_city", "cityname", "city_id="
					+ newAdRecord.getCity_id());

			newAdRecord.setCatName(catName);
			newAdRecord.setSubCatName(subCatName);
			Log.info("Setting City:" + city + " id:"
					+ newAdRecord.getCity_id());
			newAdRecord.setCity(city);
		}
	}

	private String rePublishAdInfo(Connection conn, Statement stmt, int advId,
			NewAdRecord newAdRecord) throws Exception {

		String forward = "";
		Date advDate;

		User user = (User)session.getAttribute(PortalConstants.USER);
		String statement = "select * from ads where ad_id=" + advId
				+ " and member_id=" + user.getUserId()
				+ " order by date_posted desc";

		ResultSet rs = stmt.executeQuery(statement);
		while (rs.next()) {

			Classifieds thisAd = new Classifieds();
			Statement stmt1 = conn.createStatement();
			newAdRecord.setAdId(rs.getString("ad_id"));
			newAdRecord.setMemberId(rs.getInt("member_id"));
			SimpleDateFormat sdf = new SimpleDateFormat("MMM,dd hh:mm aaa");
			TimeZone tz = TimeZone.getTimeZone("GMT+05:30");
			tz.useDaylightTime();
			sdf.setTimeZone(tz);
			advDate = rs.getTimestamp(thisAd.ADV_DATE);
			newAdRecord.setDatePosted(sdf.format(advDate));

			// Get the current date.
			Calendar today = Calendar.getInstance();
			// move to 10 days back
			today.add(Calendar.DAY_OF_YEAR, -10);
			if (today.getTime().after(advDate)) {
				// republish the adv.
				today = Calendar.getInstance();
				today.add(Calendar.DAY_OF_YEAR, +30);
				newAdRecord.setActiveUntil(new SimpleDateFormat("dd-MM-yyyy")
						.format(today.getTime()));
				forward = "housing";
			} else {
				newAdRecord.setActiveUntil(new SimpleDateFormat("yyyy.MMMMM.dd")
						.format(rs.getDate(thisAd.ADV_ACTIVEUNTIL)));
				forward = "republishexcp";
				today.setTime(advDate);
				today.add(Calendar.DAY_OF_YEAR, +10);
				request.setAttribute("reppubdate", sdf.format(today.getTime()));
			}

			newAdRecord.setSubCat_id(rs.getString(thisAd.ADV_CATID));
			newAdRecord.setContactEmail(rs.getString(thisAd.ADV_CONTACTEMAIL));
			newAdRecord.setContactName(rs.getString(thisAd.ADV_CONTACTNAME));
			newAdRecord.setContactNumber(rs.getString(thisAd.ADV_CONTACTNUM));
			newAdRecord.setPostDesc(rs.getString(thisAd.ADV_TRADEDESC));
			newAdRecord.setPrice(rs.getString(thisAd.ADV_PRICE));
			newAdRecord.setTitle(rs.getString(thisAd.ADV_TITLE));
			newAdRecord.setSquareFeet(rs.getString(thisAd.ADV_SQFT));
			newAdRecord.setHouseType(rs.getString(thisAd.ADV_HOUSETYPE));

			String isanonymize = rs.getString("isanonymize");
			if (isanonymize.equals("on")) {
				newAdRecord.setIsAnonymize("on");
			} else {
				newAdRecord.setIsAnonymize(null);
			}

			String parent_cat_id = dLookUp(stmt1, "categories",
					"par_category_id", "category_id="
							+ newAdRecord.getSubCat_id());
			int parCatId = Integer.parseInt(parent_cat_id);
			if (parCatId == 1) {
				Log.info("Setting CatType");

				request.setAttribute("catType", "housing");

			}
			newAdRecord.setCategory_id(parent_cat_id);

			String catName = dLookUp(stmt1, "categories", "name",
					"category_id=" + newAdRecord.getCategoryId());
			String subCatName = dLookUp(stmt1, "categories", "name",
					"category_id=" + newAdRecord.getSubCat_id());
			String city = dLookUp(stmt1, "lookup_city", "cityname", "city_id="
					+ newAdRecord.getCity_id());

			newAdRecord.setCatName(catName);
			newAdRecord.setSubCatName(subCatName);
			Log.info("Setting City:" + city + " id:"
					+ newAdRecord.getCity_id());
			newAdRecord.setCity(city);
		}

		return forward;
	}

	private String dLookUp(Statement stat, String table, String fName,
			String where) {
		try {
			ResultSet rs = openrs(stat, "SELECT " + fName + " FROM "
					+ table + " WHERE " + where);
			if (!rs.next()) {
				rs.close();
				return "";
			}
			String res = rs.getString(1);
			rs.close();
			return (res == null ? "" : res);
		} catch (Exception e) {
			return "";
		}
	}



	ResultSet openrs(Statement stat, String sql)
			throws java.sql.SQLException {
		ResultSet rs = stat.executeQuery(sql);
		return (rs);
	}

	private void compressFile(String realPath, File in, String fileName) {

		Image img;
		BufferedImage input = null;

		try {

			if (fileName.endsWith(".jpg") || fileName.endsWith(".JPG")) {
	      		RenderedImage img1 = (RenderedImage) JAI.create("fileload",
	      				in.getAbsolutePath());

	      		input = getBufferedImage(fromRenderedToBuffered(img1));
	      	} else if (fileName.endsWith(".gif") || fileName.endsWith(".GIF")) {

//	      		// Wrap the InputStream in a SeekableStream.
//	      		InputStream is;
//				try {
//					is = new FileInputStream(in);
//					SeekableStream s = SeekableStream.wrapInputStream(is, false);
//					// Create the ParameterBlock and add the SeekableStream to it.
//					ParameterBlock pb = new ParameterBlock();
//					pb.add(s);
//					// Perform the GIF operation
//					RenderedOp img1 = JAI.create("GIF", pb);
//					is.close();
//				} catch (FileNotFoundException e) {
//					e.printStackTrace();
//				}

	      		RenderedOp img1 = FileLoadDescriptor.create(in
						.getAbsolutePath(), null, null, null);

	      		input = getBufferedImage(img1.getAsBufferedImage());

	      	} else if (fileName.endsWith(".bmp") || fileName.endsWith(".BMP")) {

	      		//  Wrap the InputStream in a SeekableStream.
	      		InputStream is;
				try {
					is = new FileInputStream(in);

					SeekableStream s = SeekableStream.wrapInputStream(is, false);

					// Create the ParameterBlock and add the SeekableStream to it.
					ParameterBlock pb = new ParameterBlock();
					pb.add(s);

					// Perform the BMP operation
					RenderedOp img1 = JAI.create("BMP", pb);

					input = getBufferedImage(img1.getAsBufferedImage());

					is.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
	      	} else if (fileName.endsWith(".png") || fileName.endsWith(".PNG")) {

	      		// Wrap the InputStream in a SeekableStream.
	      		InputStream is;
				try {
					is = new FileInputStream(in);

					SeekableStream s = SeekableStream.wrapInputStream(is, false);

					// Create the ParameterBlock and add the SeekableStream to it.
					ParameterBlock pb = new ParameterBlock();
					pb.add(s);

					// Perform the PNG operation
					RenderedOp img1 = JAI.create("PNG", pb);

					input = getBufferedImage(img1.getAsBufferedImage());

					is.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
	      	}

			if (input == null)
				return;

			// Get Writer and set compression
			Iterator iter = ImageIO.getImageWritersByFormatName("jpg");

			if (iter.hasNext()) {

				ImageWriter writer = (ImageWriter) iter.next();
				ImageWriteParam iwp = writer.getDefaultWriteParam();
				iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
				float values[] = iwp.getCompressionQualityValues();

				iwp.setCompressionQuality(values[2]);
				String newName = realPath + "/" + "Compress" + getFileName(fileName);

				File outFile = new File(newName);
				FileImageOutputStream output;

				output = new FileImageOutputStream(outFile);
				writer.setOutput(output);
				IIOImage image =
					new IIOImage(input, null, null);
				System.out.println(
						"Writing " + values[2] + "%");
				writer.write(null, image, iwp);

				input.flush();
				output.flush();
				output.close();
				writer.dispose();
				writer = null;
				outFile = null;
				image = null;
				input = null;
				output = null;
			}
		} catch (FileNotFoundException finfExcp) {
			System.out.println(finfExcp);
		} catch (IOException ioExcp) {
			System.out.println(ioExcp);
		}
	}

	private BufferedImage getBufferedImage(Image img) {

//		if the image is already a BufferedImage, cast and return it
//		if ((img instanceof BufferedImage)) {
//			return (BufferedImage) img;
//		}

		// otherwise, create a new BufferedImage and draw the original
		// image on it
		int w = img.getWidth(null);
		int h = img.getHeight(null);
		int thumbWidth = 330;
		int thumbHeight = 250;

	    // if width is less than 330 keep the width as it is.
		if (w < thumbWidth)
			thumbWidth = w;

		// if height is less than 250 keep the height as it is.
		if (h < thumbHeight)
			thumbHeight = h;

		//if less than 330*250 then do not compress
		if (w > 330 || h > 250) {

			double imageRatio = (double) w / (double) h;
			double thumbRatio = (double) thumbWidth / (double) thumbWidth;

			if (thumbRatio < imageRatio) {
				thumbHeight = (int) (thumbWidth / imageRatio);
			} else {
				thumbWidth = (int) (thumbHeight * imageRatio);
			}
		}
		// draw original image to thumbnail image object and
		// scale it to the new size on-the-fly
		BufferedImage bi = new BufferedImage(thumbWidth, thumbHeight,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g2d = bi.createGraphics();
		g2d.drawImage(img, 0, 0, thumbWidth, thumbHeight, null);
		g2d.dispose();
		return bi;
	}

	public static BufferedImage fromRenderedToBuffered(RenderedImage img) {
		if (img instanceof BufferedImage) {
			return (BufferedImage) img;
		}

		ColorModel     cm = img.getColorModel();
		int            w  = img.getWidth();
		int            h  = img.getHeight();
		WritableRaster raster = cm.createCompatibleWritableRaster(w,h);
		boolean        isAlphaPremultiplied = cm.isAlphaPremultiplied();
		Hashtable      props = new Hashtable();
		String []      keys = img.getPropertyNames();

		if (keys != null) {
			for (int i = 0 ; i < keys.length ; i++) {
				props.put(keys[i], img.getProperty(keys[i]));
			}
		}
		BufferedImage ret = new BufferedImage(cm, raster,
				isAlphaPremultiplied,
				props);
		img.copyData(raster);
		cm = null;
		return ret;
	}

	/**
	 * @param fileName
	 * @return
	 */
	private String getFileName(String fileName) {
		String filName = fileName;
		if(!filName.endsWith(".jpg")) {
			if (filName.endsWith(".bmp")) {
				filName = filName.replaceAll(".bmp", ".jpg");
			}
			if (filName.endsWith(".jpeg")) {
				filName = filName.replaceAll(".jpeg", ".jpg");
			}
			if (filName.endsWith(".png")) {
				filName = filName.replaceAll(".png", ".jpg");
			}
			if (filName.endsWith(".gif")) {
				filName = filName.replaceAll(".gif", ".jpg");
			}
		}
		return filName;
	}

	private int getUserId(String advId, Statement stmt) {

		String statement = "select * from ads where ad_id=" + advId+" order by date_posted desc";
		int memId = 0;
		ResultSet rs = null;
		try {
			rs = stmt.executeQuery(statement);
			if(rs.next()) {
				memId = rs.getInt("member_id");
			}
		} catch (SQLException SQLExcp) {
			System.out.println(SQLExcp);
			Log.info(SQLExcp.getMessage());
		} finally {
			try {
				rs.close();
			} catch (SQLException SQLExcp) {
				System.out.println(SQLExcp);
				Log.info(SQLExcp.getMessage());
			}
		}
		return memId;
	}
}